// src/stores/authStore.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfo } from '@/types/api/user'
import type { LoginResult } from '@/types/api/auth'

export const useAuthStore = defineStore('auth', () => {
  // 获取本地存储的token userInfo
  const token = ref<string | null>(localStorage.getItem('token'))
  const userInfo = ref<UserInfo | null>(null)
  const isAuthenticated = ref<boolean>(!!token.value)
  const refreshToken = ref<string | null>(localStorage.getItem('refreshToken'))

  // 保存用户认证数据
  function setAuthData(loginResult: LoginResult) {
    token.value = loginResult.token
    userInfo.value = loginResult.userInfo
    isAuthenticated.value = true
    refreshToken.value = loginResult.refreshToken

    // 持久化存储
    localStorage.setItem('token', loginResult.token)
    localStorage.setItem('userInfo', JSON.stringify(loginResult.userInfo))
    localStorage.setItem('refreshToken', loginResult.refreshToken)
  }

  // 保存token
  function setToken(newToken: string) {
    token.value = newToken
    localStorage.setItem('token', newToken)
    isAuthenticated.value = true
  }

  // 保存用户信息
  function setUserInfo(info: UserInfo) {
    userInfo.value = info
  }

  // 保存refreshToken
  function getRefreshToken() {
    return localStorage.getItem('refreshToken')
  }

  // 清除用户认证数据
  function clearToken() {
    token.value = null
    userInfo.value = null
    isAuthenticated.value = false

    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }


  return {
    token,
    userInfo,
    isAuthenticated,
    setAuthData,
    setToken,
    setUserInfo,
    clearToken,
    getRefreshToken,
  }
})
